from . import db
import datetime

sc = db.Table()


class Fiction(db.Model):
    """小说表"""

    __tablename__ = 'fictions'
    fiction_id = db.Column(db.Integer, primary_key=True, comment='主键')
    fiction_name = db.Column(db.String(300), nullable=False, comment='小说名称')
    fiction_img_url = db.Column(db.String(1000), nullable=True, comment='小说封面')
    fiction_summary = db.Column(db.String(1000), nullable=True, comment='小说简介')
    fiction_word_number = db.Column(db.Integer, default=0, comment='小说字数')
    fiction_author = db.Column(db.String(100), nullable=True, default='佚名', comment='小说作者')
    fiction_tags = db.Column(db.String(255), nullable=True, comment='小说标签')
    create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=True, comment='最后更新时间')

    sources = db.relationship('FictionSource', backref='fictions', lazy='dynamic')

    def __repr__(self):
        return '<Fiction %r>' % self.fiction_name

    def save(self):
        if self.fiction_name == '' or self.fiction_name is None:
            raise ValueError('fiction_name is not empty or None')
        if self.fiction_id is not None and self.fiction_id > 0:
            self.update_time = datetime.datetime.now()
        else:
            self.create_time = datetime.datetime.now()

        db.session.add(self)
        return db.session.commit()


class FictionSource(db.Model):
    """小说源"""

    __tablename__ = 'fiction_sources'
    source_id = db.Column(db.Integer, primary_key=True, comment='主键')
    fiction_id = db.Column(db.Integer, db.ForeignKey('fictions.fiction_id'), index=True, comment='所属小说ID')
    source_url = db.Column(db.String(1000), nullable=False, comment='资源目录地址')
    source_name = db.Column(db.String(255), nullable=True, comment='资源名称')
    source_default = db.Column(db.Boolean, nullable=False, default=False, comment='是否是默认资源')
    source_state = db.Column(db.Boolean, nullable=False, default=False, comment='是否完本')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, comment='最后更新时间')
    last_sync_time = db.Column(db.DateTime, nullable=True, comment='最后同步时间')

    contents = db.relationship('FictionContent', backref='fiction_sources', lazy='dynamic')

    def __repr__(self):
        return '<FictionSource %r>' % self.fiction_source_name

    def save(self):
        if self.fiction_id <= 0:
            raise ValueError('fiction_id is not empty or None')
        if self.source_url == '' or self.source_url is None:
            raise ValueError('source_url is not empty or None')

        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        # 删除关联小说内容
        db.session.query(FictionContent).filter(FictionContent.source_id == self.source_id).delete()
        db.session.commit()


class FictionContent(db.Model):
    """小说内容表"""

    __tablename__ = 'fiction_contents'
    content_id = db.Column(db.Integer, primary_key=True, comment='小说内容主键')
    source_id = db.Column(db.Integer, db.ForeignKey('fiction_sources.source_id'), index=True, comment='小说源ID')
    content_title = db.Column(db.String(500), nullable=False, comment='小说标题')
    content_url = db.Column(db.String(1000), nullable=False, comment='小说地址')
    content_code = db.Column(db.String(50), nullable=False, comment='小说唯一编号')
    content_text = db.Column(db.Text, nullable=True, comment='小说内容')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, comment='最后更新时间')
    last_sync_time = db.Column(db.DateTime, nullable=True, comment='最后同步时间')

    def __repr__(self):
        return '<FictionContent %r>' % self.content_title

    def save(self):
        if self.source_id <= 0 :
            raise ValueError('source_id is not empty or None')

        if self.content_title == '' or self.content_title is None:
            raise ValueError('content_title is not empty or None')

        if self.content_url is None or self.content_url == '':
            raise ValueError('content_url is not empty or None')

        if self.content_code is None or self.content_code == '':
            raise ValueError('content_code is not empty or None')

        if self.create_time is None:
            self.create_time=datetime.datetime.now()

        if self.content_id > 0:
            self.update_time=datetime.datetime.now()

        db.session.add(self)
        db.session.commit()


class FictionCooke(db.Model):
    """储存第三方网站Cookie的表,某些网站需要Cookie才可以访问"""

    __tablename__='fiction_cookes'
    cooke_id=db.Column(db.Integer,primary_key=True, comment='主键')
    cookie_domain=db.Column(db.String(200),nullable=False, comment='适用的网站域名')
    cookie_value=db.Column(db.String(2000),nullable=True, comment='Cookie值')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, comment='最后更新时间')

    def save(self):
        db.session.add(self)
        db.session.commit()

    def resolve(self):
        """解析Cookie微字典"""
        cookies = {}
        for item in self.cookie_value.split(';'):
            s_pos = item.index('=')
            cookies[item[0:s_pos].strip()] = item[s_pos+1:]

        return cookies
